package com.lry.rpc.netty.client;

import com.lry.exception.FrameworkException;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

import static com.lry.common.CommonConstants.COLON;

@Slf4j
public class Connector {

    private static Bootstrap bootstrap;

    public static void setBootstrap(Bootstrap bootstrap) {
        Connector.bootstrap = bootstrap;
    }

    public static Channel connect(String ips) {
        String[] split = ips.split(COLON);
        return connect(InetSocketAddress.createUnresolved(split[0], Integer.parseInt(split[1])));
    }


    public static Channel connect(InetSocketAddress address) {
        ChannelFuture f = bootstrap.connect(address);
        try {
             f.await(10000, TimeUnit.MILLISECONDS);
             if(f.isSuccess()){
                 log.info("RpcClientBootstrap has started");
                 return f.channel();
             }else {
                return connect(address);
             }
        } catch (Exception e) {
            log.error("can not connect to services-server.");
            throw new FrameworkException(e, "can not connect to services-server.");
        }
    }

}
